package com.xinchao.ck_mips;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.dao.DaoHelper;
import com.xinchao.ck_mips.http.CKRxHttp;
import com.xinchao.ck_mips.utils.CheckOnOffUtil;
import com.xinchao.ck_mips.utils.DeviceType;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.HisiMachine;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.utils.W4324A88TAMachine;
import com.xinchao.ck_mips.widgets.WheelPlayView;
import com.xinchao.devicemanage.DeviceManager;
import com.xinchao.devicemanage.util.DeviceDBUtil;
import com.xinchao.devicemanage.util.DeviceInfoUtil;
import com.xinchao.machine.digital_advertise.DigitalADMachineFactory;
import com.xinchao.machine.digital_advertise.IBaseMachine;
import com.xinchao.machine.digital_advertise.SimpleMachine;

import java.text.SimpleDateFormat;

import okhttp3.OkHttpClient;

public class App extends MultiDexApplication {
    private static App sApp;
    public static IBaseMachine iBaseMachine;
    private boolean isDefaultOpenClose;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        DaoHelper.initDatabase(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sApp = this;
        //默认host
        ShareUtil.getInstance().put(CK.CK_HOST, BuildConfig.BASE_URL);
        //zx-328使用ijkplayer(videoView视频切换有黑屏);长虹Ni-Ni9可使用ijkplayer或者videoView；BOE-京东方使用videoView(ijkplayer视频卡顿不流畅)
        //通过设置WheelPlayerView.player值切换组件使用\
        if (Build.MODEL.contains("ZLP86Ni") || Build.MODEL.contains("IoT3288") || Build.MODEL.contains("3280") || Build.MODEL.contains("DS835") ) {
            //长虹主板，视美泰
            initHttpConfig();
            if (Build.MODEL.contains("3280")) {
                //新长铖设备，3280视美泰主板
                WheelPlayView.player =0;
            } else {
                //长虹，视美泰3288主板
                WheelPlayView.player = 1;
            }
        } else {
            DeviceDBUtil.initGreenDao(this);
            isDefaultOpenClose = ShareUtil.getInstance().getBoolean(CK.DEVICE_OPEN_CLOSE, isDefaultOpenClose);
            //BOE京东方
            WheelPlayView.player = 1;
            iBaseMachine = new SimpleMachine(this);
            if (!isDefaultOpenClose) {
                iBaseMachine.setVolume(ShareUtil.getInstance().getInt(CK.SP_VOLUME, CK.DEFAULT_VOLUME), AudioManager.STREAM_MUSIC);
                isDefaultOpenClose = true;
                ShareUtil.getInstance().put(CK.DEVICE_OPEN_CLOSE, isDefaultOpenClose);
            }
            DeviceManager.iBaseMachine = iBaseMachine;
            CKRxHttp.initRxHttp(iBaseMachine, BuildConfig.BASE_URL, this);
        }

        initLogger();
        initDownloadConfiger();
        Stetho.initializeWithDefaults(this);
        DeviceUtil.exitSleep(this);
        new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .build();
    }

    /**
     * 初始化网络请求配置
     */
    public void initHttpConfig() {
        //不同机型，实现方法不一
        if (DeviceUtil.getDeviceType() == DeviceType.DEVICE_OTHER_CODE) {
            //初始化设备工具
            iBaseMachine = DigitalADMachineFactory.createOrGetMachine(this);
        } else if (DeviceUtil.getDeviceType() == DeviceType.DEVICE_HI_DPT_CODE) {
            HisiMachine hisiMachine = new HisiMachine(this);
            //初始化设备工具
            iBaseMachine = DigitalADMachineFactory.createCustomMachine(hisiMachine);
        } else if (DeviceUtil.getDeviceType() == DeviceType.DEVICE_W4324A88T_A_CODE) {
            W4324A88TAMachine w4324A88TAMachine = new W4324A88TAMachine(this);
            //初始化设备工具
            iBaseMachine = DigitalADMachineFactory.createCustomMachine(w4324A88TAMachine);
        }

        DeviceDBUtil.initGreenDao(this);
        DeviceManager.iBaseMachine = iBaseMachine;

        isDefaultOpenClose = ShareUtil.getInstance().getBoolean(CK.DEVICE_OPEN_CLOSE, isDefaultOpenClose);
        if (!isDefaultOpenClose) {
            int[] time = CK.DEFAULT_ON_OFF;
            iBaseMachine.setSwitchTime(time[0], time[1], time[2], time[3]);
            DeviceInfoUtil.getInstance(this).saveDeviceOnOff(time[0], time[1], time[2], time[3]);
            CheckOnOffUtil.getInstence(this, iBaseMachine).checkOnOffTime(null);
            //   }

            iBaseMachine.setVolume(ShareUtil.getInstance().getInt(CK.SP_VOLUME, CK.DEFAULT_VOLUME), AudioManager.STREAM_MUSIC);
            isDefaultOpenClose = true;
            ShareUtil.getInstance().put(CK.DEVICE_OPEN_CLOSE, isDefaultOpenClose);
        }

        CKRxHttp.initRxHttp(iBaseMachine, BuildConfig.BASE_URL, this);
    }

    /**
     * 初始化下载配置
     */
    private void initDownloadConfiger() {
        FileDownloader.setupOnApplicationOnCreate(this)
                .connectionCreator(new FileDownloadUrlConnection.Creator(
                        new FileDownloadUrlConnection.Configuration()
                                .connectTimeout(10000).
                                readTimeout(10000)
                ));
    }

    public static App getApp() {
        return sApp;
    }

    /**
     * 初始化日志工具
     */
    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
                .tag(CK.TAG)   // (Optional) Global tag for every log. Default PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return true;
            }
        });
    }

}
